package bysun.weather.http;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import static bysun.weather.Commons.*;

/**
 * 创建HTTP链接
 */
public class ConnectionManager {

    private final static HttpParams httpParams;
    private final static ClientConnectionManager connectionManager;

    static {
        httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams,get("http.connection.timeout",CONN_TOUT));
        HttpConnectionParams.setSoTimeout(httpParams,get("http.read.timeout",READ_TOUT));
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(get("http.connection.max",MAX_CONNS));
        cm.setDefaultMaxPerRoute(get("http.connection.route.max",MAX_R_CONNS));
        connectionManager = cm;
    }

    public static HttpClient getHttpClient() {
        return new DefaultHttpClient(connectionManager, httpParams);
    }

}